import React, { useState, useEffect, FormEvent } from 'react';
import './Chat.css'
import { Button, Modal } from 'antd';

interface Message {
    user: string;
    content: string;
    type: 'text' | 'image' | 'file' | 'heartbeat';
    side: 'left' | 'right';
    fileName?: string;
    imageUrl?: string;
}

const Chat: React.FC = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [message, setMessage] = useState<string>('');
    const [messages, setMessages] = useState<Message[]>([]);
    const [socket, setSocket] = useState<WebSocket | null>(null);
    const [file, setFile] = useState<File | null>(null);
    //表情
    const emojis = ['😀', '😅', '😍', '😢', '👍', '🎉', '❤️'];

    useEffect(() => {
        const ws = new WebSocket('ws://localhost:8080');

        ws.onmessage = (event) => {
            const receivedMessage: Message = JSON.parse(event.data);
            if (receivedMessage.type === 'heartbeat') {
                // 处理心跳消息
                console.log('Received heartbeat');
                return;
            }
            setMessages((prevMessages) => [...prevMessages, receivedMessage]);
        };

        setSocket(ws);

        return () => {
            ws.close();
        };
    }, []);

    const handleSend = (event: FormEvent) => {
        
        event.preventDefault();

        if (socket && (message.trim() || file)) {
            let messageToSend: Message;

            if (file) {
                const imageUrl = URL.createObjectURL(file); // 创建URL用于显示图片
                messageToSend = {
                    user: '我',
                    content: '',
                    type: 'image',
                    side: 'right',
                    imageUrl: imageUrl
                };
            } else {
                messageToSend = {
                    user: '我',
                    content: message,
                    type: 'text',
                    side: 'right'
                };
            }

            socket.send(JSON.stringify(messageToSend));
            setMessages((prevMessages) => [...prevMessages, messageToSend]);
            setMessage('');
            setFile(null);
        }
    };
    const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
        setMessage(event.target.value);
    };
    const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            setFile(files[0]);
        }
    };

    const handleEmojiSelect = (emoji: string) => {
        setMessage((prev) => prev + emoji);
    };
    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    return (
        <div style={{ display: 'flex', flexDirection: 'row', width: '100vw', height: '100vh', overflow: 'hidden' }}>

            <div style={{
                display: 'flex',
                flexDirection: 'row',
                marginTop: '10vh',
                width: '100%',
                height: '90vh'
            }}>
                <div style={{ width: '65%', height: '100%', background: '#f1f1f1', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ flex: 1, overflowY: 'auto', marginBottom: '10px' }}>
                        {messages.map((msg, index) => (
                            <div key={index} style={{
                                display: 'flex',
                                justifyContent: msg.side === 'right' ? 'flex-end' : 'flex-start',
                                marginBottom: '10px'
                            }}>
                                <div style={{
                                    backgroundColor: msg.side === 'right' ? '#0084ff' : '#e0e0e0',
                                    color: msg.side === 'right' ? 'white' : 'black',
                                    padding: '10px',
                                    borderRadius: '10px',
                                    maxWidth: '60%',
                                    wordBreak: 'break-word',
                                    margin: '10px'
                                }}>
                                    {/* <strong></strong> {msg.content} */}
                                    {msg.type === 'image' ? (
                                        <img src={msg.imageUrl} alt="发送的图片" style={{ maxWidth: '100%', maxHeight: '200px', borderRadius: '10px' }} />
                                    ) : (
                                        msg.content
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>
                    <form onSubmit={handleSend} style={{ position: 'relative', width: '100%', height: '18%' }}>
                        <div style={{
                            position: 'fixed',
                            top: '0',
                            left: '0',
                            width: '100%',
                            height: '10vh',
                            background: '#4c85c2',
                            display: 'flex',
                            alignItems: 'center',
                            padding: '0 30px',
                            zIndex: 1000
                        }}>
                            <img src="https://pro-cs-freq.kefutoutiao.com/qbox/Fj-hbkSADU3RkFM3-27t43_LOelQ" style={{ width: '50px', height: '50px', borderRadius: '3px' }} alt="" />
                            <p style={{ fontSize: '25px', color: '#fff', marginLeft: '20px' }}>在线客服</p>
                        </div>
                        <textarea
                            value={message}
                            onChange={handleChange}
                            style={{
                                width: 'calc(100%)',
                                marginRight: '10px',
                                borderRadius: '3px',
                                border: '1px solid #ccc',
                                padding: '10px',
                                resize: 'none',
                                height: '100%',
                                boxSizing: 'border-box',
                                fontSize: '17px',

                            }}
                            rows={4}
                            placeholder="请输入您要咨询的内容"
                        />
                        <Button type="primary" onClick={showModal} style={{
                            position: 'absolute',
                            right: '120px',
                            top: '6px',
                        }}>
                            😊
                        </Button>
                        <div style={{ position: 'absolute', right: '20px', top: '-2px', width: '100px', height: '40px' }}>
                            <input
                                id="fileInput"
                                title='上传'
                                type="file"
                                accept="image/*"
                                onChange={handleFileUpload}
                                style={{
                                    position: 'absolute',
                                    right: '20px',
                                    top: '10px',
                                    width: '35px',
                                    height: '25px',
                                    border: '0',
                                }}
                            />
                            <label
                                htmlFor="fileInput"
                                style={{
                                    display: 'inline-block',
                                    position: 'absolute',
                                    right: '20px',
                                    top: '10px',
                                    backgroundColor: '#0084ff', // 背景颜色
                                    color: '#fff', // 字体颜色
                                    padding: '5px 10px', // 内边距
                                    borderRadius: '5px', // 圆角
                                    cursor: 'pointer', // 鼠标样式
                                    fontSize: '14px', // 字体大小
                                    boxShadow: '0px 2px 5px rgba(0, 0, 0, 0.2)', // 阴影效果
                                    transition: 'background-color 0.3s, transform 0.2s', // 过渡效果
                                }}
                            >
                                上传
                            </label>
                        </div>

                        <button
                            type="submit"
                            style={{
                                position: 'absolute',
                                right: '25px',
                                bottom: '10px',
                                width: '60px',
                                height: '35px',
                                color: '#000',
                                borderRadius: '10px',
                                border: '1px solid #ccc',
                                backgroundColor: '#f0f0f0',
                                boxSizing: 'border-box',
                            }}
                        >
                            发送
                        </button>
                    </form>
                </div>
                <div style={{ width: '35%', height: '100%', padding: '10px', overflowY: 'auto' }}>
                    <div style={{ width: '100%', height: '8%', lineHeight: '55px', borderBottom: '1px solid #ccc', }}>
                        <p style={{ fontSize: '20px', borderBottom: '2px solid #4c85c2', width: '90px', height: '100%', color: '#4c85c2', marginLeft: '10px', }}>常见问题</p>
                    </div>
                    <div style={{ paddingTop: '10px', lineHeight: '30px' }}>
                        <p>1. 什么是商用？</p>
                        <p>商业用途：指个人用于任何商业目的，或团体机构出于任何目的使用包图网网站素材。</p>
                        <p>例：任何明性或隐性宣传公司或产品，或为公司制作或部门汇报等都是商用，微商，淘宝、自媒体等也属商用。</p>
                        <p>2. 购买企业VIP是否可以获得商用授权?</p>
                        <p>购买企业VIP, 付款后可在线申请商业授权书，下载到本地，在授权范围内使用全程受套餐保障。</p>
                        <p>3. 如何添加子账号？</p>
                        <p>复制链接给同事, 同事登录自己的账号后点申请加入, 管理员同意方可（双方需电脑操作）。</p>
                        <p>4. 企业套餐下载素材范围：</p>
                        <p>企业套餐是不分类目(不含创意Pro)海量下载的，全站包图自产素材、全球精选素材都可以下载在购买的套餐授权范围内商用，就是不区分图片，视频，音乐的哟。</p>
                    </div>
                </div>
            </div>
            <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    {emojis.map((emoji) => (
                        <button key={emoji} onClick={() => handleEmojiSelect(emoji)} style={{ background: 'none', border: 'none', fontSize: '20px' }}>
                            {emoji}
                        </button>
                    ))}
                </div>
            </Modal>
        </div>
    );
};

export default Chat;

